package game.bluetooth;

import game.main.GameActivity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Point;

public class Cliente implements Bluetooth {
	private BluetoothDevice device;
	private OutputStream outStream;
	private InputStream inStream;
	private BluetoothSocket socket;

	public Cliente(GameActivity gameActivity) {
		try {
			device = gameActivity.getIntent().getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			socket = device.createInsecureRfcommSocketToServiceRecord(Server.uuid);
			gameActivity.setDispositivoRemoto(device.getName());
			socket.connect();
			outStream = socket.getOutputStream();
			inStream = socket.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void send(Point point) {
		try {
			outStream.write(String.format("%d,%d", point.x, point.y).getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void close() {
		try {
			if (outStream != null)
				outStream.close();
			if (inStream != null)
				inStream.close();
		} catch (Exception e) {
		}
		try {
			if (socket != null)
				socket.close();
		} catch (Exception e) {
		}

	}

	@Override
	public Point recive() { 
		try {
			byte[] bytes = new byte[1024];
			int lenght;
			lenght = inStream.read(bytes);
			String mensagemRecebida = new String(bytes, 0, lenght);

			try {
				String[] split = mensagemRecebida.split(",");
				int x = Integer.parseInt(split[0]);
				int y = Integer.parseInt(split[1]);
				return new Point(x, y);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
		}
		return null;
	}

}
